<template>
  <div class="content-analytics">
    <el-card class="page-header">
      <template #header>
        <div class="header-title">
          <h2>内容数据分析</h2>
          <div class="filter-actions">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :shortcuts="dateShortcuts"
              @change="handleDateChange"
            />
            <el-button type="primary" @click="refreshData">刷新数据</el-button>
            <el-button @click="exportData">导出报表</el-button>
          </div>
        </div>
      </template>
    </el-card>

    <!-- 数据概览 -->
    <div class="data-overview">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="data-card">
            <div class="data-card-content">
              <div class="data-value">{{ stats.totalArticles }}</div>
              <div class="data-label">内容总数</div>
            </div>
            <div class="data-trend">
              <span class="trend-value up">+{{ stats.newArticles }}</span>
              <span class="trend-label">较上期</span>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="data-card">
            <div class="data-card-content">
              <div class="data-value">{{ stats.totalViews }}</div>
              <div class="data-label">总浏览量</div>
            </div>
            <div class="data-trend">
              <span class="trend-value up">+{{ stats.viewIncrease }}%</span>
              <span class="trend-label">较上期</span>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="data-card">
            <div class="data-card-content">
              <div class="data-value">{{ stats.totalLikes }}</div>
              <div class="data-label">总点赞数</div>
            </div>
            <div class="data-trend">
              <span class="trend-value" :class="stats.likeTrend > 0 ? 'up' : 'down'">
                {{ stats.likeTrend > 0 ? '+' : '' }}{{ stats.likeTrend }}%
              </span>
              <span class="trend-label">较上期</span>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="data-card">
            <div class="data-card-content">
              <div class="data-value">{{ stats.totalComments }}</div>
              <div class="data-label">总评论数</div>
            </div>
            <div class="data-trend">
              <span class="trend-value" :class="stats.commentTrend > 0 ? 'up' : 'down'">
                {{ stats.commentTrend > 0 ? '+' : '' }}{{ stats.commentTrend }}%
              </span>
              <span class="trend-label">较上期</span>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表展示 -->
    <div class="chart-container">
      <el-row :gutter="20">
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>内容发布趋势</span>
                <el-radio-group v-model="publishType" size="small">
                  <el-radio-button label="daily">日</el-radio-button>
                  <el-radio-button label="weekly">周</el-radio-button>
                  <el-radio-button label="monthly">月</el-radio-button>
                </el-radio-group>
              </div>
            </template>
            <div ref="publishTrendChart" class="chart"></div>
          </el-card>
        </el-col>
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>内容分类分布</span>
              </div>
            </template>
            <div ref="categoryDistributionChart" class="chart"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>浏览量 TOP 10</span>
              </div>
            </template>
            <div class="rank-list">
              <div v-for="(item, index) in viewsRanking" :key="item.id" class="rank-item">
                <div class="rank-index" :class="index < 3 ? 'top' + (index + 1) : ''">{{ index + 1 }}</div>
                <div class="rank-title">{{ item.title }}</div>
                <div class="rank-value">{{ item.views }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>互动指标分析</span>
              </div>
            </template>
            <div ref="interactionChart" class="chart"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, watch } from 'vue'
import { ElMessage } from 'element-plus'
// import { initChart, getLineChartOption, getBarChartOption, getPieChartOption } from '@/utils/echarts'
// import { get } from '@/utils/request'

// 图表实例
const publishTrendChart = ref(null)
const categoryDistributionChart = ref(null)
const interactionChart = ref(null)

// 图表DOM元素
const publishTrendChartEl = ref(null)
const categoryDistributionChartEl = ref(null)
const interactionChartEl = ref(null)

// 过滤条件
const dateRange = ref([])
const publishType = ref('daily')

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 数据统计
const stats = reactive({
  totalArticles: 586,
  newArticles: 42,
  totalViews: 157893,
  viewIncrease: 8.5,
  totalLikes: 24356,
  likeTrend: 12.3,
  totalComments: 8793,
  commentTrend: -2.1
})

// 模拟数据 - 内容发布趋势
const publishTrendData = {
  daily: {
    xData: ['5/1', '5/2', '5/3', '5/4', '5/5', '5/6', '5/7'],
    series: [
      {
        name: '发布数量',
        type: 'bar',
        data: [8, 6, 5, 9, 10, 4, 7]
      }
    ]
  },
  weekly: {
    xData: ['第1周', '第2周', '第3周', '第4周'],
    series: [
      {
        name: '发布数量',
        type: 'bar',
        data: [42, 35, 48, 39]
      }
    ]
  },
  monthly: {
    xData: ['1月', '2月', '3月', '4月', '5月'],
    series: [
      {
        name: '发布数量',
        type: 'bar',
        data: [120, 132, 101, 134, 99]
      }
    ]
  }
}

// 分类分布数据
const categoryDistributionData = {
  series: {
    name: '内容分类',
    data: [
      { value: 35, name: '健康知识' },
      { value: 25, name: '运动健身' },
      { value: 18, name: '医疗资讯' },
      { value: 12, name: '饮食健康' },
      { value: 10, name: '其他' }
    ]
  }
}

// 互动指标数据
const interactionData = {
  xData: ['点赞率', '评论率', '分享率', '收藏率', '完成阅读率'],
  series: [
    {
      name: '互动指标',
      type: 'radar',
      data: [
        {
          value: [85, 65, 55, 70, 78],
          name: '总体表现',
          areaStyle: {
            color: 'rgba(64, 158, 255, 0.2)'
          },
          lineStyle: {
            width: 2
          }
        }
      ]
    }
  ]
}

// 浏览量排行榜数据
const viewsRanking = ref([
  { id: 1, title: '每天坚持这个习惯，轻松预防颈椎病', views: 15289 },
  { id: 2, title: '专家解读：高血压患者的饮食宜忌', views: 12578 },
  { id: 3, title: '居家健身指南：10分钟高效燃脂运动', views: 10985 },
  { id: 4, title: '睡眠质量差？这些方法帮你解决', views: 9253 },
  { id: 5, title: '健康生活从饮食开始：营养师的建议', views: 8743 },
  { id: 6, title: '久坐族必看：如何预防腰椎疾病', views: 7835 },
  { id: 7, title: '冬季养生指南：提高免疫力的秘诀', views: 6952 },
  { id: 8, title: '中医推荐：四季养生食谱大全', views: 6254 },
  { id: 9, title: '情绪管理：压力大时如何自我调节', views: 5789 },
  { id: 10, title: '健康体检指南：哪些项目必不可少', views: 5231 }
])

// 初始化图表
const initCharts = () => {
  // 由于缺少echarts依赖，这里暂时不初始化图表
  // 实际代码应该类似以下：
  
  // publishTrendChartEl.value = initChart(publishTrendChart.value, getBarChartOption({
  //   title: '内容发布趋势',
  //   xData: publishTrendData[publishType.value].xData,
  //   series: publishTrendData[publishType.value].series
  // }))
  
  // categoryDistributionChartEl.value = initChart(categoryDistributionChart.value, getPieChartOption({
  //   title: '内容分类分布',
  //   series: categoryDistributionData.series
  // }))
  
  // 初始化雷达图
  // interactionChartEl.value = initChart(interactionChart.value, {
  //   title: {
  //     text: '互动指标分析',
  //     left: 'center'
  //   },
  //   tooltip: {
  //     trigger: 'item'
  //   },
  //   radar: {
  //     indicator: interactionData.xData.map(name => ({ name, max: 100 })),
  //     shape: 'circle',
  //     splitNumber: 5,
  //     axisName: {
  //       color: '#666'
  //     }
  //   },
  //   series: interactionData.series
  // })
}

// 更新图表
const updateCharts = () => {
  // 更新发布趋势图表
  if (publishTrendChartEl.value) {
    publishTrendChartEl.value.setOption({
      xAxis: { data: publishTrendData[publishType.value].xData },
      series: publishTrendData[publishType.value].series
    })
  }

  // 更新分类分布图表
  if (categoryDistributionChartEl.value) {
    categoryDistributionChartEl.value.setOption({
      series: [categoryDistributionData.series]
    })
  }

  // 更新互动指标图表
  if (interactionChartEl.value) {
    interactionChartEl.value.setOption({
      radar: {
        indicator: interactionData.xData.map(name => ({ name, max: 100 }))
      },
      series: interactionData.series
    })
  }
}

// 处理日期变化
const handleDateChange = () => {
  updateCharts()
}

// 刷新数据
const refreshData = () => {
  ElMessage.success('数据已刷新')
  updateCharts()
}

// 导出报表
const exportData = () => {
  ElMessage.success('报表导出中，请稍后查看下载文件')
}

// 监听发布类型变化
watch(publishType, () => {
  updateCharts()
})

// 监听窗口大小变化，重新调整图表大小
const resizeHandler = () => {
  publishTrendChartEl.value?.resize()
  categoryDistributionChartEl.value?.resize()
  interactionChartEl.value?.resize()
}

// 生命周期钩子
onMounted(() => {
  // 设置默认日期范围为最近一个月
  dateRange.value = dateShortcuts[1].value()
  
  // 初始化图表
  setTimeout(initCharts, 100)
  
  // 添加窗口大小变化监听
  window.addEventListener('resize', resizeHandler)
})

onBeforeUnmount(() => {
  // 移除窗口大小变化监听
  window.removeEventListener('resize', resizeHandler)
})
</script>

<style scoped>
.content-analytics {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.header-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title h2 {
  margin: 0;
  font-size: 20px;
}

.filter-actions {
  display: flex;
  gap: 15px;
}

.data-overview {
  margin-bottom: 20px;
}

.data-card {
  height: 120px;
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.data-card-content {
  text-align: center;
}

.data-value {
  font-size: 28px;
  font-weight: bold;
  color: #333;
}

.data-label {
  font-size: 14px;
  color: #666;
  margin-top: 5px;
}

.data-trend {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 5px;
  font-size: 12px;
}

.trend-value {
  font-weight: 500;
}

.trend-value.up {
  color: #67c23a;
}

.trend-value.down {
  color: #f56c6c;
}

.trend-label {
  color: #909399;
}

.chart-container {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart {
  height: 350px;
}

.rank-list {
  height: 350px;
  overflow-y: auto;
  padding: 10px;
}

.rank-item {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  border-bottom: 1px solid #eee;
}

.rank-item:last-child {
  border-bottom: none;
}

.rank-index {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f4f4f5;
  color: #909399;
  border-radius: 4px;
  margin-right: 15px;
  font-weight: bold;
  font-size: 14px;
}

.rank-index.top1 {
  background-color: #f56c6c;
  color: white;
}

.rank-index.top2 {
  background-color: #e6a23c;
  color: white;
}

.rank-index.top3 {
  background-color: #409eff;
  color: white;
}

.rank-title {
  flex: 1;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 10px;
}

.rank-value {
  font-weight: bold;
  color: #606266;
}

@media (max-width: 768px) {
  .header-title {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .filter-actions {
    margin-top: 15px;
    flex-wrap: wrap;
  }
  
  .chart {
    height: 250px;
  }
}
</style>